import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:xrenovation/api/auth.api.dart';
import 'package:xrenovation/api/user.api.dart';
import 'package:xrenovation/localization/app_localizations.dart';
import 'package:xrenovation/routes.dart';
import 'package:xrenovation/utils/message_util.dart';
import 'package:xrenovation/widgets/language_switcher.dart';
import 'package:xrenovation/widgets/theme_switcher.dart';

class HeaderBox extends StatefulWidget {
  final Widget child;

  const HeaderBox({super.key, required this.child});

  @override
  State<HeaderBox> createState() => _HeaderBoxState();
}

class _HeaderBoxState extends State<HeaderBox> {
  Map<String, dynamic>? userInfo;
  bool _showMenu = false;
  bool _isLoading = true;
  final LayerLink _layerLink = LayerLink();
  OverlayEntry? _menuOverlayEntry;
  // _showLanguageSwitcher 是否展示语言切换按钮（调试用）
  final bool _showLanguageSwitcher = false;

  @override
  Widget build(BuildContext context) {
    final localizations = AppLocalizations.of(context);
    final theme = Theme.of(context);
    final isSmallScreen = MediaQuery.of(context).size.width < 768;

    return SafeArea(
      bottom: false,
      child: Scaffold(
        body:
            _isLoading
                ? const Center(child: CircularProgressIndicator())
                : Stack(
                  children: [
                    // 主内容区域
                    Padding(padding: const EdgeInsets.only(top: 56), child: widget.child),
                    // 顶部悬浮栏
                    Positioned(
                      top: 0,
                      left: 0,
                      right: 0,
                      child: ClipRect(
                        child: BackdropFilter(
                          filter: ImageFilter.blur(sigmaX: 20, sigmaY: 56),
                          child: Container(
                            height: 56,
                            color: theme.cardColor.withOpacity(0.7),
                            padding: const EdgeInsets.fromLTRB(16, 0, 12, 0),
                            child: _buildAppBar(localizations, theme, isSmallScreen),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
      ),
    );
  }

  @override
  void dispose() {
    _removeMenu();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _loadUserInfo();
    });
  }

  Widget _buildAppBar(AppLocalizations? localizations, ThemeData theme, bool isSmallScreen) {
    return CompositedTransformTarget(
      link: _layerLink,
      child: Row(
        children: [
          // 左侧logo和标题
          Row(
            children: [
              Image.asset(
                'assets/images/logo.png',
                width: 40,
                height: 40,
                errorBuilder:
                    (context, error, stackTrace) =>
                        Icon(Icons.home_work_outlined, size: 40, color: theme.colorScheme.onSurface),
              ),
              const SizedBox(width: 12),
              Text(
                localizations!.translate('app_title'),
                style: theme.textTheme.titleLarge?.copyWith(fontWeight: FontWeight.bold),
              ),
            ],
          ),
          const Spacer(),
          // 右侧用户信息
          if (userInfo != null) ...[
            GestureDetector(
              onTap: _toggleMenu,
              child: Container(
                padding: const EdgeInsets.all(8),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(20),
                  color: _showMenu ? theme.colorScheme.onSurface.withOpacity(0.1) : Colors.transparent,
                ),
                child: Row(
                  children: [
                    CircleAvatar(
                      radius: 16,
                      backgroundColor: theme.colorScheme.onSurface,
                      child: Text(
                        userInfo!['username']?.toString().substring(0, 1) ?? 'U',
                        style: TextStyle(fontSize: 14, color: theme.colorScheme.onPrimary),
                      ),
                    ),
                    if (!isSmallScreen) ...[
                      const SizedBox(width: 12),
                      Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            userInfo!['username'] ?? '',
                            style: theme.textTheme.bodyMedium?.copyWith(fontWeight: FontWeight.w600),
                          ),
                          Text(userInfo!['email'] ?? '', style: theme.textTheme.bodySmall),
                        ],
                      ),
                      const SizedBox(width: 8),
                      Icon(_showMenu ? Icons.arrow_drop_up : Icons.arrow_drop_down, size: 20),
                    ],
                  ],
                ),
              ),
            ),
            const SizedBox(width: 12),
            Container(width: 1, height: 20, color: theme.dividerColor),
            const SizedBox(width: 4),
            ThemeSwitcher(),
            if (_showLanguageSwitcher) ...[
              // const SizedBox(width: 4),
              // Container(width: 1, height: 20, color: theme.dividerColor),
              // const SizedBox(width: 10),
              const LanguageSwitcher(),
            ],
          ],
        ],
      ),
    );
  }

  Widget _buildMenuItem(IconData icon, String text, Color iconColor, {VoidCallback? onTap}) {
    final theme = Theme.of(context);

    return InkWell(
      onTap: () {
        _removeMenu();
        if (onTap != null) onTap();
      },
      borderRadius: BorderRadius.circular(6),
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
        child: Row(
          children: [
            Icon(icon, size: 20, color: iconColor),
            const SizedBox(width: 12),
            Text(text, style: theme.textTheme.bodyMedium),
            const Spacer(),
            const Icon(Icons.chevron_right, size: 20, color: Colors.grey),
          ],
        ),
      ),
    );
  }

  Future<void> _loadUserInfo() async {
    try {
      final info = await UserApi.getCachedUserInfo();
      if (mounted) {
        if (info != null) {
          setState(() {
            userInfo = info;
            _isLoading = false;
          });
        } else {
          _updateUserInfo();
        }
      }
    } catch (e) {
      _updateUserInfo();
    }
  }

  Future<void> _logout() async {
    final localizations = AppLocalizations.of(context);
    final closeLoading = MessageUtil.loading(localizations.translate('loading_text'));
    await AuthApi.logout();
    if (mounted) {
      closeLoading();
      Navigator.pushNamed(context, AppRoutes.login);
      // Navigator.of(context, rootNavigator: true).pushReplacementNamed(AppRoutes.login);
    }
  }

  void _removeMenu() {
    _menuOverlayEntry?.remove();
    _menuOverlayEntry = null;
    setState(() => _showMenu = false);
  }

  void _showUserMenu() {
    final overlay = Overlay.of(context);
    final theme = Theme.of(context);
    final localizations = AppLocalizations.of(context);
    final double menuWidth = 240;
    final double rightMargin = 10;
    final double topOffset = 56;

    _menuOverlayEntry = OverlayEntry(
      builder:
          (context) => GestureDetector(
            onTap: _removeMenu,
            behavior: HitTestBehavior.translucent,
            child: Stack(
              children: [
                Positioned.fill(child: Container(color: Colors.transparent)),
                Positioned(
                  top: topOffset,
                  right: rightMargin,
                  child: Material(
                    elevation: 8,
                    color: Colors.transparent,
                    child: Container(
                      width: menuWidth,
                      decoration: BoxDecoration(
                        color: theme.cardColor,
                        borderRadius: BorderRadius.circular(12),
                        boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.1), blurRadius: 20, spreadRadius: 2)],
                      ),
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          // 用户信息展示
                          Container(
                            padding: const EdgeInsets.all(16),
                            child: Row(
                              children: [
                                CircleAvatar(
                                  radius: 20,
                                  backgroundColor: theme.colorScheme.onSurface,
                                  child: Text(
                                    userInfo!['username']?.toString().substring(0, 1) ?? 'U',
                                    style: TextStyle(fontSize: 16, color: theme.colorScheme.onPrimary),
                                  ),
                                ),
                                const SizedBox(width: 12),
                                Expanded(
                                  child: Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      Text(
                                        userInfo!['username'] ?? '',
                                        style: theme.textTheme.bodyLarge?.copyWith(fontWeight: FontWeight.w600),
                                        overflow: TextOverflow.ellipsis,
                                      ),
                                      const SizedBox(height: 4),
                                      Text(
                                        userInfo!['email'] ?? '',
                                        style: theme.textTheme.bodySmall,
                                        overflow: TextOverflow.ellipsis,
                                      ),
                                    ],
                                  ),
                                ),
                              ],
                            ),
                          ),
                          const Divider(height: 1, thickness: 0.5, color: Colors.grey),
                          // 菜单选项
                          _buildMenuItem(
                            Icons.star_outline,
                            localizations.translate('upgrade_pro'),
                            theme.colorScheme.onSurface,
                          ),
                          _buildMenuItem(
                            Icons.person_outline,
                            localizations.translate('account'),
                            theme.colorScheme.secondary,
                          ),
                          _buildMenuItem(
                            Icons.payment_outlined,
                            localizations.translate('billing'),
                            Colors.amber[700]!,
                          ),
                          _buildMenuItem(
                            Icons.logout_outlined,
                            localizations.translate('log_out'),
                            theme.colorScheme.error,
                            onTap: () async {
                              _removeMenu();
                              final confirmed = await MessageUtil.showConfirmDialog(
                                title: localizations.translate('confirm_logout_title'),
                                message: localizations.translate('confirm_logout_message'),
                                confirmText: localizations.translate('log_out'),
                                cancelText: localizations.translate('cancel'),
                                confirmColor: theme.colorScheme.error,
                                onConfirm: _logout,
                              );
                              debugPrint('confirmed: $confirmed');
                            },
                          ),
                          const SizedBox(height: 8),
                        ],
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
    );

    overlay.insert(_menuOverlayEntry!);
    setState(() => _showMenu = true);
  }

  void _toggleMenu() {
    if (_showMenu) {
      _removeMenu();
    } else {
      _showUserMenu();
    }
  }

  Future<void> _updateUserInfo() async {
    try {
      final updatedInfo = await UserApi.updateUserInfo();
      if (!mounted) return;
      setState(() {
        userInfo = updatedInfo;
        _isLoading = false;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() => _isLoading = false);
    }
  }
}
